#include "socketthread.h"

#include "core/coredefine.h"
#include <QDateTime>
#include <QDebug>
#include <QHostAddress>
#include <QSqlQuery>


SocketThread::SocketThread(qintptr socketDescriptor, QObject *parent)
    : QThread(parent)
    , socketDescriptor_(socketDescriptor)
    , dataBuffer_(this)
    , socket_(nullptr)
{
    DEBUG_FUNC;
    // todo：解决 构造函数在主线程中，不在同一个线程
    if (!socket_.setSocketDescriptor(socketDescriptor_))
    {
        qWarning() << "Make socket error!";
    }
    connect(&dataBuffer_, &DataBuffer::receiveOne, this, &SocketThread::slotReceiveCmdMsg);
}

SocketThread::~SocketThread()
{
    DEBUG_FUNC;
}

void SocketThread::run()
{
    QString ip = socket_.peerAddress().toString().section(':', -1, -1);
    quint16 port = socket_.peerPort();
    qDebug() << "Socket connected, IP:" << ip << "Port:" << port;

    while (socket_.state() == QTcpSocket::ConnectedState)
    {
        // 从socket中读取数据
        socket_.waitForReadyRead();
        QByteArray data = socket_.readAll();

        if (data.isEmpty())
            continue;

        dataBuffer_.pushData(data);

        // 发送数据，发完就关闭连接
//        socket_.write(body);
        // socket_.waitForBytesWritten();
    }
    qDebug() << "Socket disconnected, IP:" << ip << "Port:" << port;

    socket_.close();
    deleteLater();
}

void SocketThread::sendData(const QByteArray &data)
{

}

void SocketThread::slotReceiveCmdMsg(const QString &strCMD, const QString &msg)
{
    qDebug() << "收到->" << strCMD << msg;
    TCP_CMD cmd = CSMAP_TCP_CMD_NAME.value(strCMD);
    switch (cmd)
    {
    case TCP_CMD_SINGIN:  // 注册
        break;
    case TCP_CMD_LOGIN:  // 登录
        break;
    }
}
